/**
 * Copyright (c) 2012, Hakans Pirates - 
 * Johan Andersson spaiki17@gmail.com, 
 * Mattias Lundberg lundberg.mattias@gmail.com, 
 * Samuel Sjodin sjoodin@gmail.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *  
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package pirates.terrain;

import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetManager;
import com.jme3.audio.AudioRenderer;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.input.FlyByCamera;
import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.heightmap.AbstractHeightMap;
import com.jme3.terrain.heightmap.ImageBasedHeightMap;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.util.SkyFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Johan
 */
public class TerrainState extends AbstractAppState {

	private SimpleApplication app;
	private Node rootNode;
	private AssetManager assetManager;
	private AppStateManager stateManager;
	private InputManager inputManager;
	private ViewPort viewPort;
	private BulletAppState bullet;
	private FlyByCamera flyCam;
	private Camera cam;
	private AudioRenderer audioRenderer;
	private KeyInput keyInput;
	private Vector3f lightDir = new Vector3f(-4.9236743f, -1.27054665f,
			5.896916f);
	private TerrainQuad terrain;
	private Material matRock;

	public TerrainState(SimpleApplication app) {

		this.app = app;
		this.rootNode = this.app.getRootNode();
		this.assetManager = this.app.getAssetManager();
		this.stateManager = this.app.getStateManager();
		this.inputManager = this.app.getInputManager();
		this.viewPort = this.app.getViewPort();
		this.bullet = this.stateManager.getState(BulletAppState.class);
		this.flyCam = this.app.getFlyByCamera();
		this.cam = this.app.getCamera();
		this.audioRenderer = this.app.getAudioRenderer();

		Node mainScene = new Node("Main Scene");
		rootNode.attachChild(mainScene);

		// createTerrain(mainScene);
		DirectionalLight sun = new DirectionalLight();
		sun.setDirection(lightDir);
		sun.setColor(ColorRGBA.White.clone().multLocal(1.7f));
		mainScene.addLight(sun);

		flyCam.setMoveSpeed(50);

		// cam.setLocation(new Vector3f(-700, 100, 300));
		// cam.setRotation(new Quaternion().fromAngleAxis(0.5f,
		// Vector3f.UNIT_Z));
		cam.setLocation(new Vector3f(-327.21957f, 61.6459f, 126.884346f));
		cam.setRotation(new Quaternion(0.052168474f, 0.9443102f, -0.18395276f,
				0.2678024f));

		cam.setRotation(new Quaternion().fromAngles(new float[]{
				FastMath.PI * 0.06f, FastMath.PI * 0.65f, 0}));

		Spatial sky = SkyFactory.createSky(assetManager,
				"Scenes/Beach/FullskiesSunset0068.dds", false);
		sky.setLocalScale(350);

		mainScene.attachChild(sky);
		cam.setFrustumFar(4000);
	}

	private void createTerrain(Node rootNode) {
		matRock = new Material(assetManager,
				"Common/MatDefs/Terrain/TerrainLighting.j3md");
		matRock.setBoolean("useTriPlanarMapping", false);
		matRock.setBoolean("WardIso", true);
		matRock.setTexture("AlphaMap",
				assetManager.loadTexture("Textures/Terrain/splat/alphamap.png"));
		Texture heightMapImage = assetManager
				.loadTexture("Textures/Terrain/splat/mountains512.png");
		Texture grass = assetManager
				.loadTexture("Textures/Terrain/splat/grass.jpg");
		grass.setWrap(WrapMode.Repeat);
		matRock.setTexture("DiffuseMap", grass);
		matRock.setFloat("DiffuseMap_0_scale", 64);
		Texture dirt = assetManager
				.loadTexture("Textures/Terrain/splat/dirt.jpg");
		dirt.setWrap(WrapMode.Repeat);
		matRock.setTexture("DiffuseMap_1", dirt);
		matRock.setFloat("DiffuseMap_1_scale", 16);
		Texture rock = assetManager
				.loadTexture("Textures/Terrain/splat/road.jpg");
		rock.setWrap(WrapMode.Repeat);
		matRock.setTexture("DiffuseMap_2", rock);
		matRock.setFloat("DiffuseMap_2_scale", 128);
		Texture normalMap0 = assetManager
				.loadTexture("Textures/Terrain/splat/grass_normal.jpg");
		normalMap0.setWrap(WrapMode.Repeat);
		Texture normalMap1 = assetManager
				.loadTexture("Textures/Terrain/splat/dirt_normal.png");
		normalMap1.setWrap(WrapMode.Repeat);
		Texture normalMap2 = assetManager
				.loadTexture("Textures/Terrain/splat/road_normal.png");
		normalMap2.setWrap(WrapMode.Repeat);
		matRock.setTexture("NormalMap", normalMap0);
		matRock.setTexture("NormalMap_1", normalMap2);
		matRock.setTexture("NormalMap_2", normalMap2);

		AbstractHeightMap heightmap = null;
		try {
			heightmap = new ImageBasedHeightMap(heightMapImage.getImage(),
					0.25f);
			heightmap.load();
		} catch (Exception e) {
			e.printStackTrace();
		}
		terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
		List<Camera> cameras = new ArrayList<Camera>();
		cameras.add(cam);
		terrain.setMaterial(matRock);
		terrain.setLocalScale(new Vector3f(5, 5, 5));
		terrain.setLocalTranslation(new Vector3f(0, -30, 0));
		terrain.setLocked(false); // unlock it so we can edit the height

		terrain.setShadowMode(ShadowMode.Receive);
		rootNode.attachChild(terrain);

		RigidBodyControl terrainPhysicsNode = new RigidBodyControl(
				CollisionShapeFactory.createMeshShape(terrain), 0);
		terrain.addControl(terrainPhysicsNode);
		rootNode.attachChild(terrain);
		bullet.getPhysicsSpace().add(terrainPhysicsNode);

	}
}
